package algotithm.leetcode.listnode.interview0205;

/**
 * @author zhouyanxiang
 * @Date 2021-02-2021/2/18-20:49
 * @URL https://leetcode-cn.com/problems/sum-lists-lcci/
 * @Title 面试题 02.05. 链表求和
 */

import algotithm.leetcode.listnode.ListNode;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {


    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(-1);
        ListNode node = dummy;
        int carry = 0;
        while (l1 != null || l2 != null || carry != 0) {
            if (l1 != null) {
                carry += l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                carry += l2.val;
                l2 = l2.next;
            }
            node.next = new ListNode(carry % 10);
            carry /= 10;
            node = node.next;
        }
        return dummy.next;
    }
}
